package com.jcl.recruit.api.common.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jcl.recruit.org.model.Job;
import com.jcl.recruit.org.service.JobService;
import com.jcl.recruit.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static org.springframework.beans.support.PagedListHolder.DEFAULT_PAGE_SIZE;

/**
 * @author 刘明新
 * @date 2018/8/7 上午9:15
 */
@RestController
@RequestMapping("/api/job")
public class JobController {

    @Autowired
    private JobService jobService;

    @Autowired
    private UserService userService;

    /**
     * 职位列表
     * @param token
     * @return
     */
    @RequestMapping("/find")
    public Map<String,Object> findJobs(String token,@RequestParam(value = "page", required = false, defaultValue = "1") String toPage){
        Map<String,Object> map = new LinkedHashMap<>();
        if(StringUtils.isBlank(token) || userService.selectIsLogin(token) == null){
            map.put("type","error");
            map.put("message","还没有登录");
            map.put("errors","[]");
            return map;
        }
        PageHelper.startPage(Integer.valueOf(toPage),DEFAULT_PAGE_SIZE);
        List<Map<String,Object>> jobs = jobService.selectAllJobs();
        PageInfo pageInfo = new PageInfo(jobs);
        List<Long> list = new ArrayList<>();
        list.add(pageInfo.getTotal());
        map.put("type","success");
        map.put("message","执行成功");
        map.put("jobs",pageInfo.getList());
        map.put("total",pageInfo.getTotal());
        map.put("cnt",list);
        return map;
    }

    /**
     * 保存或者修改职位
     * @param job
     * @return
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Map<String,Object> save(@RequestBody Job job){
        Map<String,Object> map = new LinkedHashMap<>();
        if(job.getId() == null) {
            job.setCreatetime(new Date());
        }
        job.setStatus(0);
        jobService.insertOrUpdate(job);
        map.put("type","success");
        map.put("message","执行成功");
        map.put("job",job);
        return map;
    }

    /**
     * 假删除职位
     * @param id
     * @return
     */
    @RequestMapping("/delete/{id}")
    public Map<String,Object> deleteId(@PathVariable("id")Integer id){
        Map<String,Object> map = new LinkedHashMap<>();
        Job job = new Job();
        job.setId(id);
        job.setStatus(-1);
        jobService.updateByPrimaryKeySelective(job);
        map.put("type","success");
        map.put("message","执行成功");
        return map;
    }
}
